<template>
  <div>
    <el-card>
      <el-form ref="form" :model="form" label-width="80px" size="mini">
        <el-form-item label="选择对象">
          <div style="display: flex;align-items: center;">
            <div
              v-for="(item,index) in nowTreeArr"
              :key="item.id"
              class="myCheck"
              name="type"
              @click="deleteType(item,index)"
            >{{ item.name }}
              <i class="el-icon-circle-close" />
            </div>
          </div>
        </el-form-item>
        <div class="formtop">
          <el-form-item
            v-if="path!=='/reportManagement/electricityFeesReport'"
            prop="day_time"
            label-width="auto"
            :rules="path==='/reportManagement/electricityFeesReport'? [
              { required: false}
            ]: [
              { required: true, message: '日期不能为空'}
            ]"

            label="日期"
          >
            <el-date-picker
              v-model="form.day_time"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item
            v-if="path==='/reportManagement/electricityFeesReport'"
            label-width="auto"
            prop="start_time"
            :rules="path!=='/reportManagement/electricityFeesReport'? [
              { required: false}
            ]: [
              { required: true, message: '开始日期不能为空'}
            ]"

            label="开始日期"
          >
            <el-date-picker
              v-model="form.start_time"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item
            v-if="path==='/reportManagement/electricityFeesReport'"
            label-width="auto"
            prop="end_time"
            :rules="path!=='/reportManagement/electricityFeesReport'? [
              { required: false}
            ]: [
              { required: true, message: '结束日期不能为空'}
            ]"

            label="结束日期"
          >
            <el-date-picker
              v-model="form.end_time"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="primary" @click="exportExcel">导出</el-button>
          </el-form-item>
        </div>
      </el-form>
      <el-tabs
        v-if="path!=='/reportManagement/electricityFeesReport'&&path!=='/reportManagement/electricParameterReport'"
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane label="日" name="day2" />
        <el-tab-pane label="月" name="month" />
        <el-tab-pane label="年" name="year" />
      </el-tabs>
      <div
        v-if="path==='/reportManagement/electricityReport'||path==='/reportManagement/powerReport'"
        style="height: 80%;"
      >
        <el-table
          v-if="tableHead.length>0"
          :data="tableData"
          style="width: 100%"
          class="table"
        >
          <el-table-column
            prop="name"
            label="测量点"
            width="250"
          />
          <el-table-column
            v-for="(v,n) in tableHead"
            :key="n"
            :prop="v"
            :label="v"
          />

        </el-table>
      </div>
      <div
        v-if="path==='/reportManagement/electricityFeesReport'"
        style="height: 80%;"
      >
        <el-table
          :data="tableData"
          style=" width: 100%"
          :span-method="objectSpanMethod"
          class="table"
        >
          <el-table-column
            prop="device_name"
            label="设备名称"
          />
          <el-table-column
            prop="total"
            label="总电量(kWh)"
          />
          <el-table-column
            prop="total_fee"
            label="总电费(元)"
          />
          <el-table-column label="尖">
            <el-table-column
              prop="jian_power"
              label="尖电量(kWh)"
            />
            <el-table-column
              prop="jian_fee"
              label="	尖电费(元)"
            />
          </el-table-column>
          <el-table-column label="峰">
            <el-table-column
              prop="feng_power"
              label="峰电量(kWh)"
            />
            <el-table-column
              prop="feng_fee"
              label="峰电费(元)"
            />
          </el-table-column>
          <el-table-column label="平">
            <el-table-column
              prop="ping_power"
              label="平电量(kWh)"
            />
            <el-table-column
              prop="ping_fee"
              label="平电费(元)"
            />
          </el-table-column>
          <el-table-column label="谷">
            <el-table-column
              prop="gu_power"
              label="谷电量(kWh)"
            />
            <el-table-column
              prop="gu_fee"
              label="谷电费(元)"
            />
          </el-table-column>
        </el-table>
      </div>
      <div
        v-if="path==='/reportManagement/electricParameterReport'"
        style="height: 80%;"
      >
        <el-table
          :data="tableData"
          style="width: 100%"
          class="table"
        >
          <el-table-column
            prop="device_name"
            label="时间段"
            width="150"
          />
          <el-table-column
            prop="total"
            label="测量点"
            width="150"
          />
          <el-table-column
            v-for="item in tableColumn"
            :key="item.id"
            :prop="item.prop"
            :label="item.name"
          >
            <template v-if="item.child">
              <el-table-column
                v-for="item1 in item.child"
                :prop="item1.prop"
                :label="item1.name"
                width="120"
              />
            </template>

          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-show="total>0"
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="form.offset"
        @current-change="changeOffest"
      />
    </el-card>
  </div>
</template>
<script>
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'
import { getReportData, getParamList } from '@/api/reportManagementApi.js'

export default {
  name: 'electricityComparisonChild',
  components: {},
  props: {
    choseData: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      tableData: [],
      options: [],
      form: {
        day_time: '',
        monitor_id: [],
        station_id: [],
        site_id: [],
        period_type: '',
        limit: 10,
        offset: 1,
        end_time: '',
        start_time: ''
      },
      activeName: 'day2',
      treeObj: [],
      value2: [],
      dropDownValue: '',
      optionsMetaAll: [],
      optionsMetaShow: [],
      valueMeta: [],
      input3: '',
      IndexGroup: [],
      nowTreeArr: [],
      optionArr: [],
      indexGroupParameterArr: [],
      chartArr: [],
      tableHead: [],
      total: 0,
      path: '',
      tableData2: [],
      tableColumn: []
    }
  },
  watch: {
    choseData: { // 监听的对象
      deep: true, // 深度监听设置为 true
      handler: function(newV, oldV) {
        if (this.path !== '/reportManagement/electricityFeesReport') {
          for (var i = 0; i < this.nowTreeArr.length; i++) {
            if (newV.id === this.nowTreeArr[i].id) {
              return
            }
          }
          this.nowTreeArr.push(newV)
          if (this.nowTreeArr.length === 1) {
            this.render()
          }
        }
        if (this.path === '/reportManagement/electricityFeesReport' || this.path === '/reportManagement/electricParameterReport') {
          this.nowTreeArr = [newV]
          this.render()
        }
      }
    },
    chartArr: { // 监听的对象
      deep: true, // 深度监听设置为 true
      handler: function(newV, oldV) {
        for (var i = 0; i < newV.length; i++) {
          this.setEnergyRanking(newV[i], i)
        }
      }
    },
    activeName: { // 监听的对象
      deep: true, // 深度监听设置为 true
      handler: function(newV, oldV) {
        if (newV) {
          this.search()
        }
      }
    }
  },
  mounted() {
    this.path = this.$route.path
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    render() {
      var date = new Date()
      date.getFullYear() // 获取完整的年份(4位)
      date.getMonth() // 获取当前月份(0-11,0代表1月)
      date.getDate() // 获取当前日(1-31)
      this.form.day_time = date.getFullYear() + '-' + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
      this.form.start_time = date.getFullYear() + '-' + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
      this.form.end_time = date.getFullYear() + '-' + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
      this.search()
    },
    changeOffest() {
      this.form.offset = arguments[0]
      this.search()
    },
    // 导出表格所用
    exportExcel() {
      if (this.tableData.length === 0) {
        this.$message({
          showClose: true,
          message: '暂无可用数据导出',
          type: 'error'
        })
        return
      }
      // 设置当前日期
      const time = new Date()
      const year = time.getFullYear()
      const month = time.getMonth() + 1
      const day = time.getDate()
      const name = year + '' + month + '' + day
      var wb = XLSX.utils.table_to_book(document.querySelector('.table'))
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          name + '.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    deleteType(v, n) {
      this.nowTreeArr.splice(n, 1)
    },
    search() {
      const _ = this
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var monitorIdArr = []
          if (this.nowTreeArr.length === 0) {
            this.$message({
              showClose: true,
              message: '请选择监控设备',
              type: 'error'
            })
            return
          }
          // 写的有点儿乱乱，后期有时间再改
          for (var i = 0; i < this.nowTreeArr.length; i++) {
            monitorIdArr.push(this.nowTreeArr[i].id)
            this.form.station_id.push(this.nowTreeArr[i].site_id)
          }

          if (this.path !== '/reportManagement/powerReport') {
            this.form.period_type = this.activeName
            this.form.monitor_id = monitorIdArr
            this.form.station_id = Array.from(new Set(this.form.station_id))
            this.form.site_id = []
          } else if (this.path === '/reportManagement/electricParameterReport') {
            this.form.period_type = this.activeName === 'day2' ? 'day' : this.activeName
            this.form.monitor_id = monitorIdArr[0]
            this.form.site_id = this.form.station_id[0]
            this.form.station_id = []
          } else if (this.path === '/reportManagement/powerReport') {
            this.form.period_type = this.activeName === 'month' ? 'month2' : this.activeName
            this.form.monitor_id = monitorIdArr
            this.form.site_id = this.form.station_id[0]
            this.form.station_id = []
          }

          if (this.path === '/reportManagement/electricParameterReport') {
            this.getTableParamList(monitorIdArr[0])
          }

          getReportData(this.$route.path, this.form).then((res) => {
            // 电量报表
            if (this.path === '/reportManagement/electricityReport' || this.path === '/reportManagement/powerReport') {
              this.tableHead = res.data.table[0].data
              var arr = []
              for (var i = 1; i < res.data.table.length; i++) {
                var obj = {}
                for (var j = 0; j < res.data.table[i].data.length; j++) {
                  obj[res.data.table[0].data[j]] = res.data.table[i].data[j]
                }
                obj.name = res.data.table[i].name
                arr.push(obj)
              }
              this.tableData = arr
              this.total = Math.ceil(res.data.count / this.form.limit)
              console.log(this.tableHead)
            } else {
              this.tableData = res.data.data
            }
          })
        } else {
          return false
        }
      })
    },
    getTableParamList(id) {
      getParamList({ monitor_id: id }).then(res => {
        this.tableColumn = res.data.data
      })
    },
    filterSearch(item) {
      return item.includes(this.dropDownValue)
    },
    handleClick(tab, event) {
      console.log(tab, event)
    }
  }
}
</script>

<style lang='scss' scoped>
::v-deep .tableHead {
  background-color: #EDF1F8 !important;
}

.formtop {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

#energyRanking, .energyRanking_box {
  width: 1309px;
  height: 40vh;
}

.bottom_box {
  width: 1309px;
  height: 50%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  & > div {
    width: 600px;
    height: 34vh;
  }
}

::v-deep .el-card__body {
  height: 100%;
}

::v-deep .el-pagination {
  display: block;
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

::v-deep .cell {
  text-align: center;
}

.myCheck {
  padding: 0 30px 0 20px;
  border: 1px solid #c6c6c6;
  border-radius: 10px;
  margin-left: 10px;
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;

  i {
    color: #c6c6c6;
    font-size: 25px;
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
  }
}

::v-deep .is-required {
  display: flex;
  align-items: center;
  margin-left: 20px;
}
</style>
